package info.emamian.droplet.core.initialize;

import info.emamian.droplet.core.services.SMSService;
import info.emamian.droplet.core.smsHandler.DrugInfoHandler;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

/**
 * makes sure mongo is available during the application startup.
 * 
 * @author Peyman
 * 
 * 
 */
@Component
public class SMSInitilization implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger log = LoggerFactory.getLogger(SMSInitilization.class);

	@Autowired
	MongoTemplate mongoTemplate;

	@Autowired
	SMSService smsService;

	@Autowired
	private ServletContext servletContext;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		log.error("===============================================================");
		log.info("SMSInitialization onApplicationEvent");
		try {
			// mongoTemplate.getDb();
			log.info("Collection sms found : {}", mongoTemplate.getCollectionNames().contains("sms"));
		} catch (Exception e) {
			// TODO: handle exception
			log.error("Mongo DB error during initialization", e);
		}
		try {
			log.info("Registered sms handler for drug : {}", smsService.registerHandler("drug", new DrugInfoHandler(event.getApplicationContext().getParent())));

		} catch (Exception e) {
			log.error("SMS service error during initialization", e);
		}
		log.error("===============================================================");

	}
}
